import Vue from 'vue'
import VueRouter from 'vue-router'
import HomePage from '../views/HomePage.vue'
import ArticleDetail from '../views/ArticleDetail.vue'
import LoginForm from '../views/LoginForm.vue'
import AdminPanel from '../views/AdminPanel.vue'
import store from '../store'

Vue.use(VueRouter)

const routes = [
    { path: '/', name: 'HomePage', component: HomePage },  // 组件名改为HomePage
    {
        path: '/article/:id',
        name: 'ArticleDetail',
        component: ArticleDetail,
        props:true
    },
    { path: '/login', name: 'LoginForm', component: LoginForm },  // 组件名改为LoginForm
    { path: '/admin', name: 'AdminPanel', component: AdminPanel, meta: { requiresAuth: true } }  // 组件名改为AdminPanel
  ]


const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
    if(!store.state.user.token) {
        next({ path:'/login',query: {redirect: to.fullPath} })
    } else {
        next()
    }
} else {
    next()
}
})

  export default router